﻿using System;
using System.Collections.Generic;
using System.Data.Entity.Validation;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using MyLocalChurch.Business;
using MyLocalChurch.Constants;
using MyLocalChurch.Models;
using MyLocalChurch.Models.KidsChurch;
using log4net;

namespace MyLocalChurch.KidsChurch
{
    public partial class GuardiansAndKids : System.Web.UI.Page
    {
        private readonly MyContext _context = MyContextSingleton.Instance;

        protected void Page_Load(object sender, EventArgs e)
        {
            var guardians = _context.Guardians.ToList();

            rptGuardians.DataSource = guardians;
            rptGuardians.DataBind();
        }

        protected void rptGuardians_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType != ListItemType.Item && e.Item.ItemType != ListItemType.AlternatingItem)
                return;

            var guardian = (Guardian)e.Item.DataItem;
            var linkBarcode = (HtmlAnchor) e.Item.FindControl("linkBarcode");
            var lblBarcode = (Label)e.Item.FindControl("lblBarcode");
            var linkCheckOut = (HtmlAnchor)e.Item.FindControl("linkCheckOut");
            var lblCheckOut = (Label)e.Item.FindControl("lblCheckOut");

            var barcode = guardian.GetValidBarcode();
            if (barcode == null)
            {
                linkBarcode.Visible = false;
                lblBarcode.Visible = true;
            }
            else
            {
                linkBarcode.Visible = true;
                lblBarcode.Visible = false;

                linkBarcode.HRef = string.Concat("/Admin/ViewBarcode.aspx?", QueryParameters.Barcode, "=",
                                                 barcode.Code);
            }

            if (CheckInOutManager.HasKidsForCheckOut(guardian))
            {
                linkCheckOut.Visible = true;
                lblCheckOut.Visible = false;
            }
            else
            {
                linkCheckOut.Visible = false;
                lblCheckOut.Visible = true;
            }
            linkCheckOut.HRef = string.Concat("CheckOut.aspx?", QueryParameters.GuardianId, "=", guardian.Id);
        }
    }
}